import React, { useState, useEffect } from 'react';
import Post from '../components/Post';
import Hotpost from '../components/Hotpost';
import './Home.css';
import { searchPostByHot } from '../api/userApi';

const Home = () => {
  const [userId, setUserId] = useState(null);
  const [hotPosts, setHotPosts] = useState([]);

  useEffect(() => {
    const storedUserId = localStorage.getItem('userId');
    if (storedUserId) {
      setUserId(storedUserId);
    }
  }, []);

  useEffect(() => {
    if (userId) {
      const fetchPosts = async () => {
        try {
          const fetchedPosts = await searchPostByHot('', userId);
          setHotPosts(fetchedPosts);
          // console.log('Fetching hot posts:', fetchedPosts);
        } catch (error) {
          console.error('Error fetching hot posts:', error);
        }
      };

      fetchPosts();
    }
  }, [userId]);

  const posts = hotPosts.map((blog) => ({
    userId: blog.userId,
    userImage: blog.userImage,
    blogImage: blog.blogImage,
    interestId:blog.interestId,
    blogId: blog.blogId, // 确保使用正确的字段名称
    title: blog.name,
    author: blog.account,
    content: blog.description,
    time: blog.updateTime,
    likeCount: blog.likesCount,
    commentCount: blog.commentsCount,
    isLiked: blog.isLiked,
    isFollowed: blog.isFollowed,
    isCollected: blog.isCollected,
  }));



  if (!hotPosts.length) {
    return <div>Loading...</div>;
  }

  return (
    <div className="home">
      <div className="home-left">
        <div className="home-body">
          <div className="posts-section">
            {posts.map((post) => (
              <Post key={post.blogId} post={post} />
            ))}
          </div>
        </div>
      </div>
      <div className="right-section">
        <Hotpost />
      </div>
    </div>
  );
};

export default Home;
